<?php
/**
 * User namagement page controller
 *
 * @author Dima
 *
 */

class Admin_ReportController extends modules_admin_controllers_ControllerBase
{
    protected $_bForLoggedUsersOnly = true;
    
//----------------------------------------------------------------------------------------------------
    
    public function init()
    {
        if (! $this->getRequest()->isXmlHttpRequest())
        {
            parent::init();
            $this->view->title = 'User Report';
        }
        
        $this->_helper->AjaxContext()->initContext('json');     
    }
    
//----------------------------------------------------------------------------------------------------

    public function indexAction()
    {
    	$this->view->headScript()->appendFile('/js/admin_report.js');   
    	       
        $aUser    = models_UserMapper::fetchAll();
        $oRequest = $this->getRequest();
        $idUser   = $oRequest->getParam('id_user');
                    
        if ('print' == $oRequest->getParam('view'))
        {
//            $this->_helper->layout->disableLayout();
            $this->view->layout()->setLayoutPath(APPLICATION_PATH . '/modules/admin/layouts/print');
            $this->view->view   = 'print';
        }

        if (isset($idUser))
        {
	        $archive          = $oRequest->getParam('archive');    
	        if ('Current month' == $archive)
                $archive = false; 
	
	        if (!$archive)
	        {
	              $startDate  = date('Y-m-1');
	              $endDate    = date('Y-m-t');
	        }  
	        else
	        {
	            $startDate    = $archive . '-1';
	            $endDate      = date('Y-m-t', strtotime($startDate));
	        }
        	
            list($year, $month, $day) = explode('-', $startDate);
            $retReport = array();
        
            $reportPeriod  = models_PeriodMapper::findByIdUser($idUser, $startDate);
	        $user          = models_UserMapper::findById($idUser);
	        $allProject    = models_ProjectMapper::findByIdUser($idUser, $startDate, $endDate);
	        $allReport     = models_ReportMapper::findByIdUser($idUser, $startDate, $endDate);
	        foreach ($allReport as $report)
	        {
	            $day = date('j', strtotime($report['date']));
	            $retReport[$day][$report['id_project']] = $report['hour'];
	        }
//	      print_r($allReport);

            $archiveDate   = models_ReportMapper::getAllArchiveDate();
            $attach        = models_PrinttimesheetMapper::findByIdUserAndDate($idUser, $year . '-' . $month . '-1');
            
            if(isset($attach[0]))    
	           $this->view->attach     = $attach[0];
	           
	        $this->view->archive      = $archive;
	        $this->view->archiveDate  = $archiveDate;   
	        $this->view->endDay       = date('t', strtotime($endDate));
	        $this->view->user         = $user;
	        $this->view->period       = date('F Y', strtotime($endDate));
	        $this->view->allProject   = $allProject;
	        $this->view->allReport    = $retReport;        
	        $this->view->month        = $month;
	        $this->view->year         = $year;
	        $this->view->reportPeriod = isset($reportPeriod[0]) ? $reportPeriod[0] : array('status' => '');
	    }
	        
        $this->view->aUser      = $aUser;   
    }
    
//----------------------------------------------------------------------------------------------------

    public function editAction()
    {
        $this->view->headLink()->appendStylesheet('/css/user.css');
        $this->view->headScript()->appendFile('/js/usertoproject.js');
        $this->view->headLink()->appendStylesheet('/css/ui-lightness/jquery-ui-1.7.2.custom.css');
        $this->view->headScript()->appendFile('/js/lib/jquery-ui.js');
        
        $oRequest = $this->getRequest();
        $oForm = new modules_default_forms_ProjectForm();

        if ($oRequest->isPost())
        {
            $aPost = $oRequest->getPost();

            $oForm->isValid($aPost);

            $aData = array(
                    'name'       =>  $oForm->getValue('name'),
                    'base'       =>  'on' == $oForm->getValue('base') ? 1 : 0 , 
                    'start_date' =>  $oForm->getValue('start_date'),
                    'end_date'   =>  $oForm->getValue('end_date'),
            );

            models_ProjectMapper::edit($this->_request->getParam('id'), $aData);
            $this->_redirect('/admin/project/');
        }
        else
        {
            $this->view->oItem = models_ProjectMapper::findById($this->_request->getParam('id'));
        }
    }
    
//----------------------------------------------------------------------------------------------------

    public function addAction()
    {
        $oRequest           = $this->getRequest();
        
        if ($oRequest->isPost())
        {
            $name                   = strip_tags($oRequest->getParam('name'));
            $base                   = strip_tags($oRequest->getParam('base'));
            
            $aData['name']          = $name;
            $aData['base']          = 'on' == $base ? 1 : 0 ;
            
            $idItem = models_ProjectMapper::save($aData);

            $this->_redirect('/admin/project');
        }
        else
        {
//            $this->view->headScript()->appendFile('/js/addcardcategory.js');
        }
    }
    
//----------------------------------------------------------------------------------------------------

    public function deleteAction()
    {
        try 
        {
            models_ProjectMapper::delete($this->_request->getParam('id'));
        } 
        catch (Exception $e) 
        {
        }
            $this->_redirect('/admin/project/');
    }
    
//----------------------------------------------------------------------------------------------------

    public function periodAction()
    {

    	$oRequest  = $this->getRequest();
    	$idUser    = $oRequest->getParam('id_user');
    	$action    = $oRequest->getParam('do_action');
    	$year      = $oRequest->getParam('year');
    	$month     = $oRequest->getParam('month');
    	
    	$id        =  models_PeriodMapper::findByIdUser($idUser, $year . '-' . $month . '-1');
    	$aData     = array('status' => $action );

    	if (isset($id[0]['id']))
    	{
    	    models_PeriodMapper::edit($id[0]['id'], $aData);
    	}
    	else
    	{
    		$aData     = array('status'   => $action,
    		                   'id_user'  => $idUser,
    		                   'date'     =>  $year . '-' . $month . '-1',
    		                   );
    		models_PeriodMapper::save($aData);
    	}
    	
        $this->_redirect('/admin/report/?id_user=' . $idUser . '&archive=' . $year . '-' . $month);
    }
    
//----------------------------------------------------------------------------------------------------

    public function attachAction()
    {

        $oRequest  = $this->getRequest();
        $idUser    = $oRequest->getParam('id_user');
        $action    = $oRequest->getParam('do_action');
        $year      = $oRequest->getParam('year');
        $month     = $oRequest->getParam('month');
        
        $id        =  models_PeriodMapper::findByIdUser($idUser, $year . '-' . $month . '-1');
//        $aData     = array('status' => $action );

        if ($oRequest->isPost())
        {
            $file_name           = strip_tags($oRequest->getParam('file_name'));
//            phpinfo();
//            die;

            if ('' != $_FILES['file_name']['name'])
            {
                $userFile    = $_FILES['file_name'];
                $tmpFile     = $userFile['tmp_name'];
                $nameFile    = $userFile['name'];
                list($name, $ext) = explode('.', $nameFile);
                
                
                $newFileName =  $year . '-' . $month . '-'. $idUser . '.' . $ext;

                $JobDir = $_SERVER['DOCUMENT_ROOT'] . '/attach';
                if( ! file_exists($JobDir))
                {
                    mkdir($JobDir) or die;
                    chmod($JobDir, octdec('0777'));
                }

                $JobDir = $_SERVER['DOCUMENT_ROOT'] . '/attach/' . $newFileName;

                if(rename($tmpFile, $JobDir ))
                {
                    chmod($JobDir, octdec('0777'));
                }

                
	            $aData['id_user']      = $idUser;
	            $aData['date']         = $year . '-' . $month . '-1';
	            $aData['file_name']    = $newFileName;
	            $id                    = models_PrinttimesheetMapper::findByIdUserAndDate($idUser, $year . '-' . $month . '-1');
	            
	            
	            if (isset($id[0]['id']))
	            {
	            	 $idItem = models_PrinttimesheetMapper::update($id[0]['id'], $aData);
	            }
	            else
	            {
	                $idItem = models_PrinttimesheetMapper::saveArray($aData, 'models_DbTable_Printtimesheet');
	            }
            }
                $this->_redirect('/admin/report');
        }

        $this->_redirect('/admin/report/');
    }

//----------------------------------------------------------------------------------------------------
    
}